require("./index.css");

var _mm = require("util/mm.js");
var template = require("./index.string");

var uploadComponent = function(){
	
	this.defaultOption = {
		container: null,
		extensionList: null
	};
	this.onUpload = null;
	this.beforeUpload = null;
	var _this = this;
	$(document).on("change", "#upload-component-real-upload-btn", function(){
		var filename = $(this).val();
		$("#upload-component-fake-upload-input").val(filename);
	});
	$(document).on("click", "#upload-component-btn-upload", function(){
		var filename = $("#upload-component-fake-upload-input").val();
		if(!filename){
			return;
		}
		typeof _this.beforeUpload === "function"
			? _this.beforeUpload() : null;
		var extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length);
		if(!_this.isContainExt(extension)){
			alert("文件类型错误");
			return;
		}
		typeof _this.onUpload === 'function' 
            ? _this.onUpload() : null;
	});
};

uploadComponent.prototype.render = function(userOption){
	//合并选项
	this.option = $.extend({}, this.defaultOption, userOption);
	if(!(this.option.container instanceof jQuery)){
		return;
	}
	this.option.container.html(this.getHtml());
};
uploadComponent.prototype.getHtml = function(){
	var htmlTemplate = _mm.renderHtml(template, {});
	return htmlTemplate;
};

uploadComponent.prototype.upload = function(resolve, reject){
	var _this = this;
	var form = $("form[name=upload-form]");
	var param = {};
	param.success = resolve;
	param.error = reject;
	var options = {
		url: _this.option.url || '',
		type: "post",
		data: _this.option.data || "",
		success: function(data) {
			data = data.replace(/<[^>]+>/g, "");
			var res = $.parseJSON(data);
			_mm.doSuccess(param, res);
		},
		error: function(err) {
			_mm.doError(param, err);
		}
	};
	form.ajaxSubmit(options);
}
uploadComponent.prototype.isContainExt = function(extension){
	var extensionList = this.option.extensionList;
	if(extensionList == null){
		//当用户没有传入文件后缀列表时修，表示所有文件类型全部接受
		return true;
	}
	for(var i = 0; i < extensionList.length; i++){
		if(extension == extensionList[i]){
			return true;
		}
	}
	return false;
}

module.exports = uploadComponent;